<template>
    <tm-upload v-model="imageValue" :maxFile="maxFile" :url="uploadUrl" :header="uploadHeader"
        v-bind="$attrs"></tm-upload>
</template>

<script setup lang="ts">
import { USE_UPLOAD_FILE_CONFIG_TYPE } from '@/tmui/tool/useFun/useUploadFile';
import { getUploadUrl } from '@/utils/env';
import { useAuthStore } from '@/state/modules/auth';
import { isArray, isString } from '@/utils/is';
const imageValue = ref<any>([])
const emits = defineEmits(['update:modelValue'])
const props = defineProps({
    modelValue: {
        type: Object,
        default: ''
    },
    onlyOne: {
        type: Boolean,
        default: false
    },
    maxFile: {
        type: Number,
        default: 9
    }
})
const uploadHeader = ref({
    token: useAuthStore().getToken
})
const uploadUrl = ref(getUploadUrl() + '/image')
watch(() => props.modelValue, () => {
    if (props.modelValue) {
        if (isArray(props.modelValue)) {
            imageValue.value = props.modelValue
        } else {
            imageValue.value = [props.modelValue]
        }
    }
})


watch(imageValue, () => {
    if (imageValue.value.length) {
        let arr = []
        imageValue.value.forEach((res: any) => {
            if (isString(res)) {
                arr.push(res)
            } else if (res.statusCode == 3) {
                if (res.response && res.response.indexOf('uri') == -1) {
                    arr.push(res.response)
                } else {
                    try {
                        let response = JSON.parse(res.response)
                        if (response.code == 1) {
                            arr.push(response.data.uri)
                        }
                    } catch (e) {

                    }
                }
            }
        })
        if (props.onlyOne) {
            emits('update:modelValue', arr[0])
        } else {
            emits('update:modelValue', arr)

        }
    }

})
</script>